package com.kpf.springcloud.service.impl;

import com.kpf.springcloud.common.CommonUtil;
import com.kpf.springcloud.common.ResponseEnum;
import com.kpf.springcloud.exception.BusinessException;
import com.kpf.springcloud.mapper.KpfPayOrderMapper;
import com.kpf.springcloud.pojo.KpfPayOrder;
import com.kpf.springcloud.pojo.KpfUser;
import com.kpf.springcloud.service.IKpfPayOrderService;
import com.kpf.springcloud.service.IKpfUserService;
import com.kpf.springcloud.service.ITokenService;
import com.kpf.springcloud.service.IWxPayService;
import com.kpf.springcloud.utils.LocalIpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author shiwen
 * @date 2021/3/11
 */
@Service
public class KpfPayOrderServiceImpl extends BaseServiceImpl<KpfPayOrderMapper, KpfPayOrder> implements IKpfPayOrderService {

    @Autowired
    private ITokenService tokenService;

    @Autowired
    private IWxPayService wxPayService;

    @Autowired
    private IKpfUserService userService;

    /**
     * 生成订单记录对象
     *
     * @param orderNo
     * @param amount
     * @param mark
     * @param payWay
     */
    @Override
    public void saveKpfPayOrder(String orderNo, int amount, int mark, int payWay) {
        String token = tokenService.verifyToken();
        if ("TOKEN_EXPIRED".equals(token)) {
            throw new BusinessException(ResponseEnum.TOKEN_EXPIRED);
        }
        int userId = Integer.parseInt(token.split("-")[0]);
        int payStatus = 0;
        if ("PAY_SUCCESS".equals(wxPayService.queryOrder(orderNo))) {
            // payStatus 订单状态 0：未付款 1：已付款 3：已退款
            payStatus = 1;
        }
        KpfPayOrder kpfPayOrder = KpfPayOrder.builder().amount(amount).clientIp(LocalIpUtils.getLocalIpAddr()).mark(mark).orderNo(orderNo)
                .payWay(payWay).userId(userId).status(payStatus).build();
        save(kpfPayOrder);
    }

}